﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
namespace Common
{
    /// <summary>
    /// 导出到CSV
    /// </summary>
    public static class ReportHelper
    {


        public static void CSV(DataTable dt)
        {
            string Filename = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";
            ReportHelper.CSV(Filename, dt);
        }

        public static void CSV(string filename, DataTable dt)
        {
            StringBuilder Str = new StringBuilder();
            char c = ',';
            StringWriter sw = new StringWriter();
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                Str.Append(dt.Columns[i].Caption + c);
            }
            Str.Append("\r\n");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    try
                    {
                        Str.Append(ConvertToSaveCell(dt.Rows[i][j]));
                    }
                    catch
                    {
                        Str.Append(c);
                    }
                }
                Str.Append("\r\n");
            }
            sw.Write(Str);
            sw.Close();
            var response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.BufferOutput = true;
            response.AddHeader("Content-Disposition", "attachment;   filename=" + filename);
            response.ContentType = "application/ms-excel";
            response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            response.Write(sw);
            sw.Dispose();
            response.Flush();
            response.End();
        }


        public static void CSV<T>(List<T> lts) where T : new()
        {
            string filename = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";
            CSV(filename, lts);
        }

        public static void CSV<T>(string filename, List<T> lts) where T : new()
        {
            StringBuilder Str = new StringBuilder();
            char c = ',';
            StringWriter sw = new StringWriter();
            //
            T t = new T();
            var properties = t.GetType().GetProperties();
            if (properties != null)
            {
                foreach (var item in properties)
                {
                    if (item.Name != "EntityState" && item.Name != "EntityKey")
                    {
                        Str.Append(item.Name + c);
                    }
                }
            }
            Str.Append("\r\n");
            if (lts != null)
            {
                foreach (var item in lts)
                {
                    properties = item.GetType().GetProperties();
                    if (properties != null)
                    {
                        foreach (var ditem in properties)
                        {
                            if (ditem.Name != "EntityState" && ditem.Name != "EntityKey")
                            {
                                var value = ditem.GetValue(item, null);
                                if (value == null)
                                {
                                    Str.Append("" + c);
                                }
                                else
                                {
                                    DateTime result = new DateTime();
                                    if (DateTime.TryParse(value.ToString(), out result))
                                    {
                                        Str.Append(result.ToShortDateString() + c);
                                    }
                                    else
                                    {
                                        if (value == null || string.IsNullOrEmpty(value.ToString()))
                                        {
                                            Str.Append(c);
                                        }
                                        else
                                        {
                                            Str.Append(ConvertToSaveCell(value));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    Str.Append("\r\n");
                }
            }
            sw.Write(Str);
            sw.Close();
            var response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.BufferOutput = true;
            response.AddHeader("Content-Disposition", "attachment;   filename=" + filename);
            response.ContentType = "application/ms-excel";
            response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            response.Write(sw);
            sw.Dispose();
            response.Flush();
            response.End();
        }

        /// <summary>
        /// 空格，双引号等照原输出，逗号换成中文
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static string ConvertToSaveCell(object cell)
        {
            var cellStr = "";
            if (cell != null) cellStr = cell.ToString();
            cellStr = cellStr.Replace(",", "，").Trim();
            cellStr = cellStr.Replace("\"", "\"\"");
            return "\"" + cellStr + "\"" + ",";
        }

    }
}
